package jsyf.oa.service.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import jsyf.com.util.DateUtils;
import jsyf.oa.dao.system.LeaveDao;
import jsyf.oa.dao.system.SignInDao;
import jsyf.oa.dao.system.TargetDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.system.LeaveEntity;
import jsyf.oa.entity.system.TargetEntity;
import jsyf.oa.facade.system.LeaveFacade;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.LEAVE_NOTICE;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.LEAVE_NOTICE_SELF;

/**
 * Created by WHH-PC on 2018/1/9.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class LeaveService implements LeaveFacade {
    @Autowired
    private LeaveDao leaveDao;
    @Autowired
    private TargetDao targetDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private SignInDao signInDao;
    @Autowired
    private TokenDao tokenDao;

    @Override
    public String save(String jsonData) {
        LeaveEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), LeaveEntity.class);
        entity.setCreateUserId(entity.getUserId());
        entity.setRemark(entity.getRemark());
        //请假天数
        Integer days = DateUtils.daysBetween(entity.getBeginTime(), entity.getEndTime());
        Calendar c = Calendar.getInstance();
        c.setTime(entity.getBeginTime());

        //请假日期 1号,2号..
        String dateInterval = "";

        JSONObject jsonUser = userDao.getViewJSONById(entity.getUserId());
        if (jsonUser != null) {
            entity.setCompanyId(jsonUser.get("companyId").toString());
        }
        if (days == 0) {
            //请假1天
            String leaveDate = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
            entity.setLeaveDate(leaveDate);
            entity.setAm(0.5);
            entity.setPm(0.5);
            dateInterval = DateUtils.parse(c.getTime(), "d") + "号";
            //删除当天的签到信息
            signInDao.removeByCondition(" AND SIGN_DATE = ?  AND USER_ID = ? ", new String[]{leaveDate, entity.getUserId()});
            //删除当天的请假信息
            leaveDao.removeByCondition(" AND LEAVE_DATE = ?  AND USER_ID = ? ", new String[]{leaveDate, entity.getUserId()});
            //查询某人某天是否已请过假
            List<JSONObject> leaveList = leaveDao.getJSONListByCondition(" AND LEAVE_DATE = ? AND USER_ID = ?", new Object[]{leaveDate, entity.getUserId()});
            if (leaveList == null || Integer.valueOf(leaveList.size()) == 0) {
                leaveDao.add(entity);
            }
            //清空请假当天的电访、面访目标
            List<JSONObject> targetList = targetDao.getJSONListByCondition("  AND TARGET_DATE=? AND USER_ID=?", new Object[]{leaveDate, entity.getUserId()});
            if (targetList.size() > 0) {
                String targetId = targetList.get(0).get("id").toString();
                TargetEntity targetEntity = (TargetEntity) targetDao.getIBaseEntityById(targetId);
                targetEntity.setFaceTarget(0);
                targetEntity.setTelTarget(0);
                targetDao.update(targetEntity);
            }
        } else {
            //请假多天
            for (Integer i = 0; i <= days; i++) {
                String leaveDate = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
                entity.setLeaveDate(leaveDate);
                dateInterval += DateUtils.parse(c.getTime(), "d") + "号，";
                entity.setAm(0.5);
                entity.setPm(0.5);
                c.add(Calendar.DAY_OF_MONTH, 1);// +1天
                //删除当天的签到信息
                signInDao.removeByCondition(" AND SIGN_DATE = ?  AND USER_ID = ? ", new String[]{leaveDate, entity.getUserId()});
                //删除当天的请假信息
                leaveDao.removeByCondition(" AND LEAVE_DATE = ?  AND USER_ID = ? ", new String[]{leaveDate, entity.getUserId()});
                //查询某人某天是否已请过假
                List<JSONObject> leaveList = leaveDao.getJSONListByCondition(" AND LEAVE_DATE = ? AND USER_ID = ?", new Object[]{leaveDate, entity.getUserId()});
                if (leaveList == null || Integer.valueOf(leaveList.size()) == 0) {
                    leaveDao.add(entity);
                }
                //清空请假当天的电访、面访目标
                List<JSONObject> targetList = targetDao.getJSONListByCondition("  AND TARGET_DATE=? AND USER_ID=?", new Object[]{leaveDate, entity.getUserId()});
                if (targetList.size() > 0) {
                    String targetId = targetList.get(0).get("id").toString();
                    TargetEntity targetEntity = (TargetEntity) targetDao.getIBaseEntityById(targetId);
                    targetEntity.setFaceTarget(0);
                    targetEntity.setTelTarget(0);
                    targetDao.update(targetEntity);
                }
            }
            dateInterval = dateInterval.substring(0, dateInterval.length() - 1);
        }

        //企业号:发送请假消息
        JSONObject msgObject = new JSONObject();
        msgObject.put("userIds", userDao.getWeChatMsgIds(entity.getUserId()));
        msgObject.put("content", String.format(LEAVE_NOTICE, userDao.getUserMainInfo(entity.getUserId()), dateInterval, entity.getRemark()));
        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

        //企业号:发送请假消息给自己
        JSONObject msgObject2Self = new JSONObject();
        msgObject2Self.put("userIds", entity.getCreateUserId());
        msgObject2Self.put("content", String.format(LEAVE_NOTICE_SELF, userDao.getUserMainInfo(entity.getUserId()), dateInterval, entity.getRemark()));
        tokenDao.sendTextMsg(JSON.toJSONString(msgObject2Self));

        return StringUtils.isNotEmpty(entity.getId()) ? entity.getId() : "";
    }

    @Override
    public JSONObject getLeaveByDay(String userId, String signDate) {
        List<JSONObject> list;
        if (signDate.isEmpty()){
            //查询 >= 今天的请假记录
            signDate = DateUtils.getBeforeDate(new Date(), 0);
            list = leaveDao.getJSONListByCondition(" AND USER_ID = ? AND LEAVE_DATE >= ? ", new Object[]{userId, signDate});
        }else{
            //查询当天签到信息
            list = leaveDao.getJSONListByCondition(" AND USER_ID = ? AND LEAVE_DATE = ? ", new Object[]{userId, signDate});
        }
        return list.size() > 0 ? list.get(0) : null;
    }


    @Override
    public String delLeaveByDay(String userId, String signDate) {
        //销假
        Integer result = leaveDao.removeByCondition(" AND USER_ID = ? AND LEAVE_DATE >= ? ", new String[]{userId, signDate});
        return result + "";
    }

}

